package com.zqh.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.zqh.gateway.redis.RedisUtil;
import com.zqh.myfmmall.result.Result;
import com.zqh.myfmmall.utils.JwtUtil;
import jdk.nashorn.internal.ir.debug.JSONWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;


/**
 * @Description :
 * @Author :kono淇杭哒、
 * @Create 2022-02-19 15:31
 */
@Component
@Order(-1)
public class CheckTokenFilter implements GlobalFilter{
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        Object ignoreCheckToken = exchange.getAttributes().get("ignoreCheckToken");
        ServerHttpResponse response = exchange.getResponse();
        //获取token
        String token = exchange.getRequest().getHeaders().getFirst("token");
        if(token != null){
            //只要带有token就进行续命
            redisUtil.expire(token,RedisUtil.DEFAULT_TIMEOUT);
        }
        //判断当前服务是否需要检验token，对于像登录，注册等服务放行
        if (ignoreCheckToken != null) {
            return chain.filter(exchange);
        }
        if (token == null) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }else{
            int verify = JwtUtil.verify(token);
            //token不合法
            if (verify != 1) {
                response.getHeaders().add("Content-Type","application/json;charset=utf-8");
                byte[] bytes = JSON.toJSONString(Result.againLogin()).getBytes(StandardCharsets.UTF_8);
                DataBuffer buffer = response.bufferFactory().wrap(bytes);
                return response.writeWith(Mono.just(buffer));
//                response.setStatusCode(HttpStatus.UNAUTHORIZED);
//                return response.setComplete();
            }
            //token合法
            return chain.filter(exchange);
        }
    }

}
